package testharness;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;

public abstract class ConcurrentHarness {

	protected static final int CYCLES =1000000;
	
	ExecutorService executor;
	
	
	public ConcurrentHarness() {
		super();
	}
	
	protected void submitTasks() {
		for (int i = 0; i < CYCLES; i++) {
			executor.submit(newTask());
		}
	}
	
	@Before
	public void initExecutor() {
		executor = new ThreadPoolExecutor(4, 4, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(CYCLES));
	}

	@After
	public void collectResult() throws InterruptedException {
		waitAllTasks();
		checkResults();
	}

	private void waitAllTasks() throws InterruptedException {
		executor.shutdown();
		boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS);
		assertTrue("Finished all tasks", terminated);
	}

	abstract protected Runnable newTask(); 	
	
	abstract public void checkResults();
	
}